/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

package stattracker;

import javax.swing.*;

import com.sun.image.codec.jpeg.JPEGCodec;
import com.sun.image.codec.jpeg.JPEGEncodeParam;
import com.sun.image.codec.jpeg.JPEGImageEncoder;

import java.net.URL;
import java.net.MalformedURLException;
import java.io.IOException;
import java.awt.Graphics;
import java.awt.Image;
import java.awt.Container;
import java.awt.image.BufferedImage;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.InputStreamReader;

/**
 *
 * @author mattcrain
 */
public class MyUtils 
{
	public static final String INVALID_GT = "!GT";
	private static final String GT_CAPITALIZATION = "<li><h3>";
	private static final int AVERAGE_TIME = 400;
	protected static final double BYTES_TO_MB = 1048576;
	//The following are used to format time
	private static final int secPerYear = 31556926, secPerMonth = 2629744, secPerWeek = 604800, perDay = 86400, perHour = 3600, perMin = 60;

	//Tests to see if a String is empty
	public static boolean emptyString(String test){
		return (test == null || test.isEmpty());
	}

	protected static ImageIcon createImageIcon(String path, String description)
	{
		java.net.URL imgURL = Halo3Frame.class.getResource(path);
		if(imgURL != null) 
		{
			return new ImageIcon(imgURL, description);
		} 
		else
		{
			new ErrorMessage("Couldn't find file: " + path);
			System.err.println("Couldn't find file: " + path);
			return null;
		}
	}

	//Goes the the URL and gets the image
	public static JLabel getImage(String url, String defaultURL)
	{
		try
		{
			ImageIcon icon = new ImageIcon(new URL(url));
			return new JLabel(icon);
		}
		catch(Exception e)
		{
			return new JLabel(MyUtils.createImageIcon(defaultURL, ""));
		}
	}

	public static JScrollPane makeScroll(JComponent panel)
	{
		JScrollPane pane = new JScrollPane(panel, JScrollPane.VERTICAL_SCROLLBAR_ALWAYS, JScrollPane.HORIZONTAL_SCROLLBAR_AS_NEEDED);
		pane.getVerticalScrollBar().setUnitIncrement(50);
		pane.getVerticalScrollBar().setBlockIncrement(150);
		return pane;
	}


	//returns a scaled imaged from the URL
	public static JLabel getScaledImage(String url, double scale) throws MalformedURLException, IOException
	{
		URL imgLoc = new URL(url);
		ImageIcon test = new ImageIcon(imgLoc);
		Container c = new Container();
		Image example = c.createImage((java.awt.image.ImageProducer)imgLoc.getContent());
		test = new ImageIcon(example.getScaledInstance((int)(test.getIconHeight()/scale), (int)(test.getIconWidth()/scale), Image.SCALE_AREA_AVERAGING));
		return new JLabel(test);
	}

	/**
	 * This checks to see if a gamertag has data on Bungie's website
	 * It also corrects any capitalization mistakes the user may have made
	 * @param gt
	 * @return
	 */
	public static String BungieCheck(String gt)
	{
		String gamerTag = gt;
		try
		{
			String url = "http://www.bungie.net/Stats/Halo3/Default.aspx?player=" +
			gamerTag.replaceAll(" ", "%20");
			URL test = new URL(url);
			BufferedReader in = new BufferedReader(new InputStreamReader(test.openStream()));
			String inline;
			int lineNum = 0;
			while((inline = in.readLine()) != null && lineNum < 300)
			{
				if(inline.contains(GT_CAPITALIZATION) && !inline.contains("People Finder"))
				{
					int start = inline.indexOf(GT_CAPITALIZATION) + GT_CAPITALIZATION.length();
					gamerTag = inline.substring(start, inline.indexOf("-")-1);
				}
				if(inline.contains("Halo 3 Service Record Not Found"))
					gamerTag = INVALID_GT;
				lineNum++;
			}
		}
		catch(MalformedURLException u){gamerTag = INVALID_GT;}
		catch(IOException i){gamerTag = INVALID_GT;}
		return gamerTag;
	}

	public static int parseSec(String len)
	{
		int hrs = 0, min = 0, sec = 0;
		try
		{
			hrs = Integer.parseInt(len.substring(0,2)) * 3600;
			min = Integer.parseInt(len.substring(3,5)) * 60;
			sec = Integer.parseInt(len.substring(6, len.length()));
		}
		catch(NumberFormatException e)
		{
			return AVERAGE_TIME;
		}
		return (hrs + min + sec);
	}

	public static String formatTime(int sec)
	{
		int temp;
		String time = "";

		temp = sec/secPerYear; //Yeas
		if(temp > 0)
		{
			time += temp + " Year";
			if(temp > 1)
				time += "s";
			time += ", ";
		}

		temp = (sec%secPerYear)/secPerMonth; //Months
		if(temp > 0)
		{
			time += temp + " Month";
			if(temp > 1)
				time += "s";
			time += ", ";
		}

		temp = ((sec%secPerYear)%secPerMonth)/secPerWeek; //Weeks
		if(temp > 0)
		{
			time += temp + " Week";
			if(temp > 1)
				time += "s";
			time += ", ";
		}

		temp = (((sec%secPerYear)%secPerMonth)%secPerWeek)/perDay; //Days
		if(temp > 0)
		{
			time += temp + " Day";
			if(temp > 1)
				time += "s";
			time += ", ";
		}

		temp = ((((sec%secPerYear)%secPerMonth)%secPerWeek)%perDay)/perHour; //Hours
		if(temp > 0)
		{
			time += temp + " Hour";
			if(temp > 1)
				time += "s";
			time += ", ";
		}

		temp = (((((sec%secPerYear)%secPerMonth)%secPerWeek)%perDay)%perHour)/perMin;
		if(temp > 0)
		{
			time += temp + " Minute";
			if(temp > 1)
				time += "s";
			time += ", ";
		}

		temp = (((((sec%secPerYear)%secPerMonth)%secPerWeek)%perDay)%perHour)%perMin;
		time += temp + " Second";
		if(temp != 1)
			time += "s";
		time += " ";
		time += "= " + String.format("%.2f hrs.",((double)sec)/perHour);
		return time;
	}




	//The Following is all for converting visible JComponents into .jpg files.
	//THE COMPONENT MUST BE CURRENTLY DISPLAYED TO BE SAVEABLE
	public static void saveComponentAsJPEG(JComponent component, File file)
	{
		Image capturedImage = component.createImage(component.getWidth(), component.getHeight());
		if(capturedImage == null)
			new ErrorMessage("Couldn't create the image. :(");
		else
			saveImageAsJPEG( capturedImage, file, component);
	}

	private static void saveImageAsJPEG(Image capturedImage, File file, JComponent component)
	{
		FileOutputStream out = null;
		try
		{
			out = new FileOutputStream( file);
		}
		catch(FileNotFoundException e)
		{
			new ErrorMessage(e);
		}

		Graphics captureG = capturedImage.getGraphics();
		component.paint( captureG);
		JPEGImageEncoder encoder = JPEGCodec.createJPEGEncoder( out);
		BufferedImage bufferedImage = (BufferedImage)capturedImage; 
		JPEGEncodeParam param = encoder.getDefaultJPEGEncodeParam( bufferedImage);

		//the first parameter here is the "quality v file size" trade-off
		//play with this value (0-1) to determine the best results for you
		param.setQuality(1.0f, true);
		try
		{
			encoder.encode( bufferedImage, param);
		}
		catch(IOException e)
		{
			new ErrorMessage(e);
		}
		try
		{
			out.flush();
		}
		catch(IOException e)
		{
			new ErrorMessage(e);
		}
		try
		{
			out.close();
		}
		catch(IOException e)
		{
			new ErrorMessage(e);
		}
	}

}
